/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.itip.event.send;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.apache.log4j.Logger;

/**
 * <p>
 * Description: 通过socket发送事件
 * </p>
 *
 * @author wangyazhou
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-8-13 下午3:05:57          wangyazhou        1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public class AlertSender {

    private static final Logger logger = Logger.getLogger(AlertSender.class);

    private static int DEFAULT_TIMEOUT = 1 * 60 * 1000;

    private static AlertSender instance = null;

    private static Object _lock = new Object();

    private AlertSender() {

    }

    public static synchronized AlertSender getInstance() {
        if (instance == null) {
            synchronized (_lock) {
                instance = new AlertSender();
            }
        }
        return instance;
    }

    /**
     * 发送事件  并返回结果 
     * @param request
     * @param host
     * @param port
     * @return
     * @throws Exception
     */
    public Object send(Object request, String host, int port) {
        Socket socket = null;
        try {
            socket = createSocket(host, port);
            socket.setSoTimeout(DEFAULT_TIMEOUT);
            writeObject(socket, request);

            //读取返回结果  非必需
            return readObject(socket);
        } catch (ConnectException ie) {
            logger.error(ie);
        } catch (Exception ie) {
            logger.error(ie);
        } finally {
            closeSocket(socket);
        }
        return null;
    }

    /**
     * 创建socket连接
     *
     * @param host
     * @param port
     * @return
     * @throws java.io.IOException
     */
    Socket createSocket(String host, int port) throws java.io.IOException, java.net.SocketTimeoutException, java.nio.channels.IllegalBlockingModeException, java.lang.IllegalArgumentException {
        Socket socket = new Socket();
        SocketAddress addr = new InetSocketAddress(host, port);
        socket.connect(addr, 10000);
        return socket;
    }

    /**
     * 发送消息
     * @param socket
     * @param  request
     * @throws Exception
     */
    void writeObject(Socket socket, Object request) throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
        oos.writeObject(request);
        oos.flush();
    }

    /**
     * 读取消息 
     * @param socket
     * @return 
     * @throws Exception
     */
    Object readObject(Socket socket) throws Exception {
        Object result = null;
        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
        result = ois.readObject();
        return result;
    }

    /**
     * 关闭socket
     * @param socket
     */
    void closeSocket(Socket socket) {
        if (socket != null) {
            InputStream is = null;
            OutputStream os = null;
            try {
                is = socket.getInputStream();
            } catch (Throwable t) {
                logger.error(t);
            }
            try {
                os = socket.getOutputStream();
            } catch (Throwable t) {
                logger.error(t);
            }

            if (is != null) {
                try {
                    is.close();
                } catch (Throwable t) {
                    logger.error(t);
                }
            }
            if (os != null) {
                try {
                    os.close();
                } catch (Throwable t) {
                    logger.error(t);
                }
            }

            try {
                socket.close();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }

    public static void main(String[] args) {
        //        StringBuilder builder = new StringBuilder("<?xml version='1.0' encoding='UTF-8'?>");
        //        builder.append("<ITSM>");
        //        builder.append("<EVENT EVENT_ID='1' JOB_ID='1' NODE_ID='1' IP='192.168.1.1' NODE_TYPE='ORACLE' TITLE='内存告警' DESCRIPTION='当前CPU利用率为65%，超过设定的60%的阈值' SEVERITY='2' STATUS='1' CREATE_TIME='2012-10-29 10:00:00' />");
        //        builder.append("</ITSM>");
        AlertSender.getInstance().send("haha", "10.0.66.73", 2425);
    }

}
